package com.biz.primus.ms.commodity.dao.specification;

import com.biz.primus.base.enums.vendor.VendorType;
import com.biz.primus.commodity.vo.backend.CommodityQueryVo;
import com.biz.primus.ms.commodity.dao.po.Product;
import com.biz.primus.ms.commodity.dao.po.SaleTag;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.List;

/**
 * @author 江南
 * @usage
 * @reviewer
 * @since 2017/2/10
 */
public class CommoditySpecification implements Specification<Product> {

    private CommodityQueryVo reqVo;

    public CommoditySpecification(CommodityQueryVo reqVo) {
        this.reqVo = reqVo;
    }

    @Override
    public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        // 按照创建时间倒序
        query.orderBy(cb.desc(root.get("createTimestamp")));
        // 查询未删除的
        predicates.add(cb.equal(root.get("deleteFlag").as(Boolean.class), Boolean.FALSE));
        if (reqVo.getVendorType() != null) {
            predicates.add(cb.equal(root.get("productType").as(VendorType.class), reqVo.getVendorType()));
        }
        if (StringUtils.isNotBlank(reqVo.getProductName())) {
            Predicate predicate = cb.like(root.get("name").as(String.class), "%" + reqVo.getProductName() + "%");
            predicates.add(predicate);
        }
        if (reqVo.getSaletagId() != null) {
            ListJoin<Product, SaleTag> join = root.join(root.getModel().getList("saleTags", SaleTag.class), JoinType.LEFT);
            predicates.add(cb.equal(join.get("id").as(Long.class), reqVo.getSaletagId()));
        }

        if (reqVo.getCategoryId() != null) {
            Predicate predicate = cb.equal(root.get("brandId"), reqVo.getCategoryId());
            predicates.add(predicate);
        }
        if (reqVo.getBrandId() != null) {
            Predicate predicate = cb.equal(root.get("categoryId"), reqVo.getCategoryId());
            predicates.add(predicate);
        }
        if (StringUtils.isNotBlank(reqVo.getProductCode())) {
            Predicate predicate = cb.equal(root.get("productCode"), reqVo.getProductCode());
            predicates.add(predicate);
        }
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        return query.getRestriction();
    }
}
